package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.dongdongshop.config.AlipayConfig;
import com.dongdongshop.dataConfig.ResponseStatus;
import com.dongdongshop.dataConfig.dataResult;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.OrderItemService;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.service.PayLogService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.shiro.SecurityUtils;
import org.omg.CORBA.TIMEOUT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("order")
public class OrderController {
    private Logger logger  = LoggerFactory.getLogger(OrderController.class);
    @Reference
    private OrderService orderService;
    @Reference
    private PayLogService payLogService;
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Reference
    private OrderItemService orderItemService;

    @RequestMapping("getSubmit")
    @ResponseBody
    public dataResult getSubmit(Double total){
        try {
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            Map<String,Object> map = orderService.getSubmit(user,total);
            System.out.println(map);
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName(),map);
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }

    /*获取订单页面数据*/
    @RequestMapping("getDTO")
    @ResponseBody
    public dataResult getDTO(){
        try {
            TbUser user = (TbUser)SecurityUtils.getSubject().getPrincipal();
            List<OrderItemDTO> list = orderService.getDTO(user);
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName(),list);
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }

    @RequestMapping("toRefund")
    @ResponseBody
    public dataResult toRefund(Long orderId){
        try {
            PayLogVo payLogVo = payLogService.toRefund(orderId);
            return new dataResult(ResponseStatus.SUCCESS.getIndex(), ResponseStatus.SUCCESS.getName(),payLogVo);
        }catch (Exception e){
            logger.error("查询失败",e);
            return new dataResult(ResponseStatus.SERVER_ERROR.getIndex(),ResponseStatus.SERVER_ERROR.getName());
        }
    }


















    //支付

    @RequestMapping("tradepay")
    @ResponseBody
    //商户订单号，商户网站订单系统中唯一订单号，必填//付款金额，必填//订单名称，必填//商品描述，可空
    public String tradepay(String WIDout_trade_no,String WIDtotal_amount,String WIDsubject,String WIDbod ){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDout_trade_no +"\","
                + "\"total_amount\":\""+ WIDtotal_amount +"\","
                + "\"subject\":\""+ WIDsubject +"\","
                + "\"body\":\""+ WIDbod +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = null;
        try {
            //检验
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            logger.error(e.toString());
        }
        //输出
        return result;
    }

    @RequestMapping("notifyUrl")
    @ResponseBody
    //商户订单号//支付宝交易号//交易状态
    public String notifyUrl(HttpServletRequest request, String out_trade_no, String trade_no, String trade_status){
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";

            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            logger.error(e.toString());
        }

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        if(signVerified) {//验证成功

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                System.out.println(trade_no);

                String tradeNo = out_trade_no;
                Double total  = Double.parseDouble(params.get("total_amount"));
                /*本地事物处理修改支付状态,发送mq进行积分增加*/
                orderService.sendMq(tradeNo,total,trade_no);


                System.out.println("异步回调------>>>交易成功 ");
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }
            return "success";

        }else {//验证失败
            System.out.println("验证失败");
            return "fail";

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }

    @RequestMapping("returnUrl")
    public String returnUrl(HttpServletRequest request, String out_trade_no, String trade_no, String total_amount, Model model){
        /* *
         * 功能：支付宝服务器同步通知页面
         * 日期：2017-03-30
         * 说明：
         * 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
         * 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。


         *************************页面功能说明*************************
         * 该页面仅做页面展示，业务逻辑处理请勿在该页面执行
         */

        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        /*mq发送延时消息,判断支付状态*/
        //String out_trade_no, String trade_no,
      /*  TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        String username = user.getUsername();*/
        Map<String,Object> map = new HashMap<>();
        map.put("out_trade_no",out_trade_no);
        map.put("trade_no",trade_no);
      /*  map.put("username",username);*/
        /*rocketMQTemplate.convertAndSend("paystatu",map);*/

        boolean signVerified = false; //调用SDK验证签名
        try {
            //验签,数字签名
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            logger.error(e.toString());
        }

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //String out_trade_no, String trade_no, String total_amount
            model.addAttribute("out_trade_no",out_trade_no);
            model.addAttribute("trade_no",trade_no);
            model.addAttribute("total_amount",total_amount);
            return "paysuccess";
        }else {
            return "payfail";
        }
    }

    @RequestMapping("tradeQuery")
    @ResponseBody
    //参数::商户订单号，商户网站订单系统中唯一订单号//请二选一设置
    public String tradeQuery(String WIDTQout_trade_no,String WIDTQtrade_no){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDTQout_trade_no +"\","+"\"trade_no\":\""+ WIDTQtrade_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            logger.error(e.toString());
        }
        //输出
        return result;
    }

    /*退款*/
    @RequestMapping("tradeRefund")
    @ResponseBody
    public String tradeRefund(String WIDTRout_trade_no,String WIDTRtrade_no,String WIDTRrefund_amount
            ,String WIDTRrefund_reason,String WIDTRout_request_no,Double itemId) throws AlipayApiException {
        //获得初始化的AlipayClient

        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDTRout_trade_no +"\","
                + "\"trade_no\":\""+ WIDTRtrade_no +"\","
                + "\"refund_amount\":\""+ WIDTRrefund_amount +"\","
                + "\"refund_reason\":\""+ WIDTRrefund_reason +"\","
                + "\"out_request_no\":\""+ WIDTRout_request_no +"\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();
        orderItemService.updateStatu(itemId);
        //输出
        return result;
    }

    /*退款查询*/
    @RequestMapping("refundQuery")
    @ResponseBody
    public String refundQuery(String WIDRQout_trade_no,String WIDRQtrade_no,String WIDRQout_request_no){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeFastpayRefundQueryRequest alipayRequest = new AlipayTradeFastpayRefundQueryRequest();

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDRQout_trade_no +"\","
                +"\"trade_no\":\""+ WIDRQtrade_no +"\","
                +"\"out_request_no\":\""+ WIDRQout_request_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            logger.error(e.toString());
        }

        //输出
        return result;
    }

    /*订单关闭*/
    @RequestMapping("tradeClose")
    @ResponseBody
    public String tradeClose(String WIDTCout_trade_no,String WIDTCtrade_no){
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeCloseRequest alipayRequest = new AlipayTradeCloseRequest();
        //请二选一设置

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ WIDTCout_trade_no +"\"," +"\"trade_no\":\""+ WIDTCtrade_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            logger.error(e.toString());
        }

        //输出
        return result;
    }


}
